﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace PrGrSerwerRozproszony
{
    public class Client
    {
        private TcpClient tcpClient;
        private StreamReader reader;
        private StreamWriter writer;

        private int userId;

        public List<Message> receivedMessages;

        public Client()
        {
            receivedMessages = new List<Message>();
        }   

        public class Message 
        {
            public int from, to;
            public string msg;
            public Message(int from, int to, string msg)
            {
                this.from = from;
                this.to = to;
                this.msg = msg;
            }
        }

        public bool ConnectToServer(string hostname, int port, int userId)
        {
            try
            {
                tcpClient = new TcpClient(hostname, port);
                reader = new StreamReader(tcpClient.GetStream());
                writer = new StreamWriter(tcpClient.GetStream());

                this.userId = userId;
                writer.WriteLine("" + userId + MainLoop.DELIMETER + "pass");
                writer.Flush();

                Thread thread = new Thread(new ParameterizedThreadStart(ThreadStart));
                thread.Start(null);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public void ThreadStart(object obj)
        {
            try
            {
                while (true)
                {
                    string line = reader.ReadLine();
                    string[] parsedLine = line.Split(MainLoop.DELIMETER);

                    Console.WriteLine("MSG RECEIVED: " + line);

                    receivedMessages.Add(new Message(int.Parse(parsedLine[0]), int.Parse(parsedLine[1]),
                        parsedLine[2]));
                }
            }
            catch (Exception ex)
            {
            }
        }

        public void SendMessageToClient(int toClientId, string msg)
        {
            string toSend = "" + userId + MainLoop.DELIMETER + toClientId + MainLoop.DELIMETER + msg;
            writer.WriteLine(toSend);
            writer.Flush();
        }

    }
}
